import numpy as np
import matplotlib.pyplot as plt
from rk45 import cal_temperature
import time
from data_record import data_record
R_1 = 0.0012
R_2 = 0.0093
C_in = 1100000
C_wall = 186000000
theta_out = -20
dt = 10


cal_temp = []
dr = []
# init
for i in range(600):
    cal_temp.append(cal_temperature(dt, R_1, R_2, C_in, C_wall))
    dr.append(data_record(i,'test'))
    if(i%2 == 0):
        cal_temp[i].reset_B_P()
    else:
        cal_temp[i].reset_B_0()

    cal_temp[i].reset_out_tempurature(theta_out)
    cal_temp[i].set_start_theta(np.random.uniform(18, 22), 14.808)

# cal

limit_device_num = int(215)
# limit_device_num = int(429)

out_flag = False


last_time = time.time()

for index in range(int((3600*4)/dt)):
    # if(out_flag is True):
    #     break
    all_temp = np.zeros((600))
    if(index%(6)==0):
        for i in range(600):
            all_temp[i] = cal_temp[i].get_theta()[0,0]
            dr[i].data_append(index,cal_temp[i].get_theta()[0,0],cal_temp[i].get_theta()[1,0],cal_temp[i].P_status)
            cal_temp[i].reset_B_0()
            if(all_temp[i] < 18):
                out_flag = True
        result = np.argpartition(all_temp, limit_device_num)
        for k in result[:limit_device_num]:
            if(all_temp[k] < 22):
                cal_temp[k].reset_B_P()
    for i in range(600):
        cal_temp[i].rk45()


print(~out_flag)
# read data and plot
for i in range(600):
    # dr[i].data_dump()

    plot_data = dr[i].data_get()
    x_axis = plot_data[:,0]/360
    temp_in = plot_data[:,1]
    temp_wall = plot_data[:,2]
    P_status = plot_data[:,3]
    plt.plot(x_axis,temp_in)
    plt.plot(x_axis,temp_wall)
    # plt.plot(x_axis,P_status)
    plt.plot(x_axis,P_status)

plt.show()

